import { useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Row,
  Col,
  Upload,
  message,
  Checkbox,
  Modal,
  Space,
} from 'antd';
import {
  LoadingOutlined,
  CloseOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import PswUpdate from './pswUpdate';
import ImgQuick from '@/pages/admin/imgQuick';
import ItemSelect from '@/components/ItemSelect';
import request from '@/utils/request';

const { confirm } = Modal;
const apiUrl = '/api/services/app/User/';
const apiUrlRole = '/api/services/app/Role/';
const UserEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [fileList, setFileList] = useState<any[]>([]);
  const [disabled, setDisabled] = useState(false);
  const [datas, setDatas] = useState<any>({});
  const [Roles, setRoles] = useState([]);
  const formRef = useRef<any>({});
  const intl = useIntl();

  useEffect(() => {
    fetchUser();
    fetchRoles();
  }, []);

  const fetchUser = () => {
    const { currentUser } = props;
    if (currentUser) {
      getUserById(currentUser.id);
    }
  };

  const getUserById = (Id: number) => {
    request(apiUrl + 'Get', {
      method: 'GET',
      params: { Id },
    }).then((response) => {
      if (response && response.success) {
        const datas = response?.result;
        if (datas) {
          const fileList: any = [];
          if (datas.avater) {
            const obj = {
              uid: datas.avater,
              name: datas.avater,
              response: {
                result: datas.avater,
              },
              status: 'done',
              url: UploadUtil.getOssFile + datas.avater,
            };
            fileList.push(obj);
          }
          setFileList(fileList);
          setDatas(datas);
          setDisabled(false);
          if (formRef.current) {
            formRef.current.setFieldsValue({ user: datas });
          }
        }
      }
    });
  };

  const fetchRoles = () => {
    request(apiUrlRole + 'GetAll', {
      method: 'GET',
      params: { SkipCount: 0, MaxResultCount: 100 },
    }).then((response) => {
      if (response && response.success) {
        const resp = response?.result;
        if (resp) {
          const Roles = response.result.items;
          setRoles(Roles);
        }
      }
    });
  };

  const onFinish = async (values: any) => {
    setLoading(true);
    const user = values.user;
    let act = 'Update';
    if (user.id == 0 || !user.id) {
      act = 'Create';
      user.password = '123456';
    }
    if (imageUrl) {
      user.avater = imageUrl;
    }
    request(apiUrl + act, {
      method: act === 'Create' ? 'POST' : 'PUT',
      data: user,
    }).then((response) => {
      if (response && response.success) {
        message.success(intl.formatMessage({ id: 'pages.saveSuccess' }));
      }
      setLoading(false);
    });
  };

  const handleUploadList = (info: any) => {
    if (info.file.status == 'error') {
      message.error(info.file.response.error.message);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} ${intl.formatMessage({ id: 'pages.upload.success' })}`);
    }
    setFileList(info.fileList);
  };

  const handleAdd = () => {
    setDisabled(true);
    setImageUrl('');
    setFileList([]);
    formRef.current.resetFields();
  };

  const handleDel = () => {
    if (datas.userName == 'admin') {
      message.error(intl.formatMessage({ id: 'pages.adminDeleteError' }));
    } else {
      request(apiUrl + 'Delete', {
        method: 'DELETE',
        data: { Id: datas.id },
      }).then((response) => {
        if (response && response.success) {
          message.success(intl.formatMessage({ id: 'pages.delete.success' }));
          props.refresh();
          formRef.current.resetFields();
        }
      });
    }
  };

  const delConfirm = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        handleDel();
      },
      onCancel() {},
    });
  };

  const getUserByName = (item: any) => {
    if (item) {
      getUserById(item?.id);
    }
  };

  const switchModal = (visible: boolean) => {
    setVisible(visible);
  };

  const clickFun = (val: any) => {
    const fileList = [];
    const obj = {
      uid: val,
      name: val,
      response: {
        result: val,
      },
      status: 'done',
      url: UploadUtil.getOssFile + val,
    };
    fileList.push(obj);
    setImageUrl(val);
    setFileList(fileList);
    setVisible(false);
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 10 },
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">{intl.formatMessage({id: 'pages.upload'})}</div>
    </div>
  );
  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.userName' }),
      dataIndex: 'userName',
    },
    {
      title: intl.formatMessage({ id: 'pages.fullName' }),
      dataIndex: 'fullName',
    },
  ];

  return (
    <Form {...layout} ref={formRef} onFinish={onFinish}>
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item label={intl.formatMessage({ id: 'pages.userName' })}>
            <Input.Group compact>
              <Form.Item
                name={['user', 'userName']}
                noStyle
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.enterUserName' }) }]}
              >
                <Input style={{ width: 100 }} />
              </Form.Item>
              <Form.Item noStyle>
                <ItemSelect
                  width={500}
                  control="User"
                  columns={columns}
                  text={intl.formatMessage({ id: 'pages.select' })}
                  title={intl.formatMessage({ id: 'pages.selectUser' })}
                  act="GetLists"
                  setCurrent={getUserByName}
                />
              </Form.Item>
            </Input.Group>
          </Form.Item>
          <Form.Item name={['user', 'id']} style={{ display: 'none' }}>
            <Input />
          </Form.Item>
          <Form.Item name={['user', 'avater']} style={{ display: 'none' }}>
            <Input />
          </Form.Item>
          <Form.Item
            name={['user', 'empID']}
            label={intl.formatMessage({ id: 'pages.empID' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'pages.enterOrSelectEmp' }) }]}
          >
            <Input style={{ width: '50%' }} />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.name' })}>
            <Input.Group compact>
              <Form.Item
                noStyle
                name={['user', 'name']}
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.enterSurname' }) }]}
              >
                <Input style={{ width: '50%' }} placeholder={intl.formatMessage({ id: 'pages.surname' })} />
              </Form.Item>
              <Form.Item
                noStyle
                name={['user', 'surname']}
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.enterName' }) }]}
              >
                <Input style={{ width: '50%' }} placeholder={intl.formatMessage({ id: 'pages.name' })} />
              </Form.Item>
            </Input.Group>
          </Form.Item>

          <Form.Item
            name={['user', 'fullName']}
            label={intl.formatMessage({ id: 'pages.fullName' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'pages.enterFullName' }) }]}
          >
            <Input style={{ width: '50%' }} />
          </Form.Item>

          <Form.Item
            name={['user', 'emailAddress']}
            rules={[{ required: true, message: intl.formatMessage({ id: 'pages.enterEmail' }) }]}
            label={intl.formatMessage({ id: 'pages.email' })}
          >
            <Input />
          </Form.Item>
          <Form.Item name={['user', 'roleNames']} label={intl.formatMessage({ id: 'pages.systemRole' })}>
            <Select mode="multiple">
              {Roles.map((item: any) => {
                return (
                  <Select.Option key={item.id} value={item.normalizedName}>
                    {item.displayName}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: layout.labelCol.span }}>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                {intl.formatMessage({ id: 'pages.save' })}
              </Button>
              <Button type="dashed" icon={<PlusOutlined />} onClick={handleAdd}>
                {intl.formatMessage({ id: 'pages.add' })}
              </Button>
              <Button
                type="primary"
                danger
                icon={<CloseOutlined />}
                onClick={delConfirm}
                disabled={disabled}
              >
                {intl.formatMessage({ id: 'pages.delete' })}
              </Button>
              <Button type="default" onClick={() => setVisible2(true)} disabled={disabled}>
                {intl.formatMessage({ id: 'pages.changePassword' })}
              </Button>
            </Space>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name={['user', 'address']} label={intl.formatMessage({ id: 'pages.address' })}>
            <Input />
          </Form.Item>
          <Form.Item name={['user', 'telphone']} label={intl.formatMessage({ id: 'pages.telphone' })}>
            <Input />
          </Form.Item>
          <Form.Item name={['user', 'isActive']} label={intl.formatMessage({ id: 'pages.active' })} valuePropName="checked">
            <Checkbox />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.avatar' })}>
            <Upload
              action={UploadUtil.uploadOSS}
              headers={{
                Authorization: UploadUtil.accessToken,
              }}
              data={{
                objectId: datas.id,
                objectName: 'user',
                objectField: 'avater',
              }}
              listType="picture-card"
              fileList={fileList}
              multiple={true}
              beforeUpload={UploadUtil.beforeUpload}
              onChange={handleUploadList}
            >
              {fileList.length >= 1 ? null : uploadButton}
            </Upload>
            <Button onClick={() => setVisible(true)}>
              {<FormattedMessage id="pages.Picture.Select" />}
            </Button>
            <Modal
              title={<FormattedMessage id="pages.changePassword" />}
              visible={visible2}
              onOk={() => setVisible2(false)}
              onCancel={() => setVisible2(false)}
              footer={null}
              destroyOnClose={true}
            >
              <PswUpdate userId={datas.id} />
            </Modal>
          </Form.Item>
        </Col>
      </Row>
      <Modal
        title={intl.formatMessage({ id: 'pages.Picture.Select' })}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => setVisible(false)}
        width={750}
        footer={false}
      >
        <ImgQuick clickFun={(val: any) => clickFun(val)} ext=".jpg,.jpeg,.png,.gif" />
      </Modal>
    </Form>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(UserEdit);
